package com.itfreer.bpm.workflow.service.skip;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.itfreer.bpm.flow.api.IBpmProjectEntity;
import com.itfreer.bpm.flow.api.IUserNextTaskUser;
import com.itfreer.bpm.history.entity.BpmHistoryEntity;
import com.itfreer.bpm.messager.BpmMessage;
import com.itfreer.bpm.option.para.NextTaskInfo;
import com.itfreer.bpm.option.para.NextTaskType;
import com.itfreer.bpm.option.para.OptionInfo;
import com.itfreer.bpm.option.para.OptionType;
import com.itfreer.bpm.option.para.TaskInfo;
import com.itfreer.bpm.option.para.TaskType;
import com.itfreer.bpm.power.para.UserInfo;
import com.itfreer.bpm.workflow.drive.IWorkFlowDrive;
import com.itfreer.bpm.workflow.option.SignCommonTask;
import com.itfreer.bpm.workflow.option.SignMultiTask;
import com.itfreer.bpm.workflow.service.BpmWorkFlowCommonSignImp;
import com.itfreer.bpm.workflow.userrole.IUserRole;
import com.itfreer.bpm.workflow.utils.BpmApprovalHistoryUtil;
import com.itfreer.bpm.workflow.utils.BpmHistoryEditUtil;
import com.itfreer.bpm.workflow.utils.BpmHistoryQueryUtil;
import com.itfreer.bpm.workflow.utils.BpmNextTaskUtils;
import com.itfreer.bpm.workflow.utils.BpmUserAuthUtils;

/**
 * 流程节点跳转实现
 * @author gj
 *
 */
@Component
public class BpmWorkFlowSkipImp {
	
	/**
	 * 流程驱动服务
	 */
	@Autowired
	protected IWorkFlowDrive workFlowDrive;
	
	/**
	 * 构建历史帮转工具
	 */
	@Autowired
	BpmHistoryEditUtil historyEditUtl;
	
	/**
	 * 构建用户审批历史
	 */
	@Autowired
	BpmApprovalHistoryUtil approvalUtil;
	
	/**
	 * 用户授权工具
	 */
	@Autowired
	BpmUserAuthUtils userAuthUtils;
	
	/**
	 * 审批过程查询接口
	 */
	@Autowired
	BpmHistoryQueryUtil historyQueryUtil;
	
	/**
	 * 用户角色接口
	 */
	@Autowired
	IUserRole userRole;
	/**
	 * 用户自定义操作下一步审批人接口
	 */
	@Autowired(required=false)
	IUserNextTaskUser userNextTaskUser;
	
	/**
	 * 下一个环节工具
	 */
	@Autowired
	BpmNextTaskUtils nextTaskUtils;
	/**
	 * 单节点会签提交
	 */
	@Autowired
	SignMultiTask signmultiTask;
	
	/**
	 * 通用流程驱动操作
	 */
	@Autowired
	BpmWorkFlowCommonSignImp commonSign;
	
	/**
	 * 多节点选择节点
	 */
	@Autowired
	SignCommonTask signCommonTask;
	
	/**
	 * 获取流程跳转节点
	 * @param bpmkey
	 * @param entity
	 * @param editHistory
	 * @param user
	 * @return
	 */
	public OptionInfo getSkipTask(String bpmkey, IBpmProjectEntity entity, List editHistory, UserInfo user) {
		OptionInfo info=new OptionInfo();
		info.setbpmkey(bpmkey);
		String sexeid=entity.getSexeid();
		info.setSexeid(sexeid);
		
		HashMap<String,Object> work_where=new HashMap<String,Object>();
		work_where.put("sexeid:=", sexeid);
		//检查校验是否是超级管理员
		if(!user.isSuperAdmin()) {
			work_where.put("toptassigneese:like",user.getUserId());
		}
		List<BpmHistoryEntity>toWorkList= historyQueryUtil.getWorkEntitys(null, work_where, null, 1000, 1);
		
		//处理当前环节
		List<TaskInfo> ctasks=new ArrayList<TaskInfo>();
		for(BpmHistoryEntity work:toWorkList) {
			TaskInfo task=new TaskInfo();
			task.setTaskdefinedid(work.gettaskdefid());
			task.setTaskName(work.gettaskdefname());
			ctasks.add(task);
		}
		info.setcTask(ctasks);
		
		//处理掉下一个环节信息
		String ctaskid=null;
		if(toWorkList!=null && toWorkList.size()>0) {
			ctaskid=toWorkList.get(0).gettaskdefid();
		}
		HashMap<String, Object> skipWhere=new HashMap<String, Object> ();
		skipWhere.put("sexeid:=", sexeid);
		HashMap<String, Integer> skipOrder=new HashMap<String, Integer> ();
		skipOrder.put("opttime", 0);
		
		String skipTaskid=",";
		
		List<BpmHistoryEntity> skiplst= new ArrayList<BpmHistoryEntity>();
		List<BpmHistoryEntity> allHistory=historyQueryUtil.getEntitys(null, skipWhere, skipOrder, 10000, 1);
		if(allHistory!=null && allHistory.size()>0) {
			for(int k=0;k<allHistory.size();k++) {
				BpmHistoryEntity iHistory=allHistory.get(k);
				if(ctaskid.equals(iHistory.gettaskdefid())) {
					if(k>1 && "退回".equals(allHistory.get(k-1).getoptresult())) {
						if(!skipTaskid.contains(iHistory.gettaskdefid()+",")){
							skipTaskid=skipTaskid+iHistory.gettaskdefid()+",";
							skiplst.add(iHistory);
						}

					}
				}
			}
		}
		
		NextTaskInfo nextTaskInfo=new NextTaskInfo();
		if(skiplst!=null && skiplst.size()>0) {
			for(BpmHistoryEntity ih:skiplst) {
				TaskInfo itask=new TaskInfo();
				itask.setTaskName(ih.getfromtaskdefname());
				itask.setTaskdefinedid(ih.getfromtaskdefid());
				UserInfo iuser=new UserInfo();
				iuser.setUserId(ih.getfromassigneesid());
				iuser.setUserName(ih.getfromassigneesname());
				iuser.setUserOrgCode(ih.getfromorgid());
				iuser.setUserOrgName(ih.getfromorgname());
				iuser.setUserSelected(true);
				itask.getUser().add(iuser);
				nextTaskInfo.getNextTask().add(itask);
			}
		}
		if(nextTaskInfo.getNextTask()!=null && nextTaskInfo.getNextTask().size()>0) {
			nextTaskInfo.getNextTask().get(0).setTaskSelect(true);
			nextTaskInfo.getNextTask().get(0).setAllUserSelect();
			if(nextTaskInfo.getNextTask().size()>1) {
				//nextTaskInfo.setNextTaskType(NextTaskType.InclusiveTask);
				info.setOptiontype(OptionType.ExclusiveSkip);
			}else {
				info.setOptiontype(OptionType.CommonSkip);
			}
			info.setNextTask(nextTaskInfo.getNextTask());
		}
		return info;
	}
	
	/**
	 * 项目跳转
	 */
	public BpmMessage skipTask(OptionInfo oInfo, IBpmProjectEntity entity, UserInfo user) {
		return this.skip(oInfo, entity, user, "跳转",null);
	}
	
	public BpmMessage skip(OptionInfo oInfo, IBpmProjectEntity entity, UserInfo user,String optionName,String bpmStatus) {
		BpmMessage message=new BpmMessage();
		
		HashMap<String,Object> work_where=new HashMap<String,Object>();
		work_where.put("sexeid:=", oInfo.getSexeid());
		//检查校验是否是超级管理员
		if(!user.isSuperAdmin()) {
			work_where.put("toptassigneese:like",user.getUserId());
		}
		List<BpmHistoryEntity>toWorkList= historyQueryUtil.getWorkEntitys(null, work_where, null, 1000, 1);
		//检查项目是否拥有权限
		if(toWorkList==null || toWorkList.size()<1) {
			message.setStatus(false);
			message.setMessage("没有项目审核的权限");
			return message;
		}
		HashMap<String, Object> allWrok=new HashMap<String,Object>(); 
		allWrok.put("sexeid:=", oInfo.getSexeid());
		List<BpmHistoryEntity>allToWork= historyQueryUtil.getWorkEntitys(null, allWrok, null, 1000, 1);
		String bestHistoryStatus="21";
		if(allToWork.size()==toWorkList.size()) {
			bestHistoryStatus="21";
		}else {
			bestHistoryStatus="2";
		}
		
		//查询最新的项目记录
		String o_sassignees="";
		HashMap<String,Object> overwork_where=new HashMap<String,Object>();
		overwork_where.put("sexeid:=", oInfo.getSexeid());
		BpmHistoryEntity overWrokH=historyQueryUtil.getOverWorkEntitys(null, overwork_where, null, 1, 1).get(0);
		o_sassignees=overWrokH.getsassignees();
		
		//处理项目来源问题
		String fromTaskName="";
		String fromTaskID="";
		if(toWorkList.size()==1) {
			fromTaskName=toWorkList.get(0).gettaskdefname();
			fromTaskID=toWorkList.get(0).gettaskdefid();
		}else {
			boolean imulti=true;
			for(BpmHistoryEntity iwork:toWorkList) {
				if(iwork.getTasktype().equals(TaskType.CommonTask)) {
					imulti=false; 
				}
				if(fromTaskName==null) {
					fromTaskName=iwork.gettaskdefname();
					fromTaskID=iwork.gettaskdefid();
				}else {
					if(!fromTaskID.contains(iwork.gettaskdefid())) {
						fromTaskName=","+iwork.gettaskdefname();
						fromTaskID=","+iwork.gettaskdefid();
					}
				}
			}
			if(imulti) {
				fromTaskName=toWorkList.get(0).gettaskdefname();
				fromTaskID=toWorkList.get(0).gettaskdefid();
			}
		}
		
		//处理提交操作(工作流需要这些操作)
		HashMap<String, Object>ComValue=new HashMap<String, Object>();
		if(oInfo.getNextTask()!=null && oInfo.getNextTask().size()>0) {
			for(TaskInfo itask: oInfo.getNextTask()) {
				if(itask.isTaskSelect()) {
					ComValue.put(itask.getTaskdefinedid(), optionName);
				}
			}
		}
		
		//保存已经产生的历史项目
		//处理前端不带回审批历史问题的表单问题
		List<BpmHistoryEntity> lst=oInfo.getEditHistory();
		if(lst==null || lst.size()<1) {
			for(BpmHistoryEntity iwork:toWorkList) {
				lst.add(iwork);
			}
		}
		boolean findNewest=false;
		for(BpmHistoryEntity history : lst) {
			
			if(history.gethistorystatus()!=null 
					&& history.gethistorystatus().trim().contains("2")) {
				findNewest=true;
			}
			
			history.setoptresult(optionName);
			history.setoptassigneesid(user.getUserId());
			history.setoptassigneesname(user.getUserName());
			history.setoptorgid(user.getUserOrgCode());
			history.setoptorgname(user.getUserOrgName());
			history.setopttime(new Date());
			history.sethistorystatus("0");
			
			if(oInfo.getNextTask()==null || oInfo.getNextTask().size()<1) {
				if("结束".equals(history.getNexttask())) {
					history.sethistorystatus("20");
					String sassignees=","+user.getUserId()+","+user.getUserName();
					if(o_sassignees==null) {
						
					}else if(!o_sassignees.contains(sassignees)){
						sassignees=sassignees+","+o_sassignees;
					}else {
						sassignees=o_sassignees;
					}
					history.setsassignees(sassignees);
				}
			}
			
		}
		historyEditUtl.updateList(lst);
		
		//没有查询到最新的记录(已办项逻辑，所有创建的第一条记录为永远的待办记录)
		if(!findNewest) {
			if("21".equals(overWrokH.gethistorystatus())) {
				overWrokH.sethistorystatus("1");
			}else if("20".equals(overWrokH.gethistorystatus())){
				overWrokH.sethistorystatus("0");
			}else {
			}
			historyEditUtl.updateEntity(overWrokH);
		}
		this.excuteSkip(oInfo, entity, user, o_sassignees, overWrokH, fromTaskName, fromTaskID, ComValue, bestHistoryStatus,bpmStatus);
		return message;
	}
	
	/**
	 * 环节提交工作
	 * @param oInfo
	 * @param entity
	 * @param user
	 * @param o_sassignees
	 * @param overWrokH
	 * @param fromTaskName
	 * @param fromTaskID
	 * @param ComValue
	 */
	private void excuteSkip(OptionInfo oInfo, IBpmProjectEntity entity, UserInfo user, String o_sassignees,
			BpmHistoryEntity overWrokH, String fromTaskName, String fromTaskID, 
			HashMap<String, Object> ComValue,String historyStatus,String bpmStatus) {
		int index=0;
		List<BpmHistoryEntity> addlst=new ArrayList<BpmHistoryEntity>();
		List<BpmHistoryEntity> updatelst=new ArrayList<BpmHistoryEntity>();
		for(TaskInfo itask:oInfo.getNextTask()) {
			if(itask.isTaskSelect()) {
				HashMap<String, Object> where=new HashMap<String, Object>();
				where.put("sexeid:=", oInfo.getSexeid());
				where.put("taskdefid:=",  oInfo.getNextTask().get(0).getTaskdefinedid());
				where.put("historystatus:in",  "1,21,2");//查询项目要么是待办处理，要么是最新待办，要么是最新，不是待办
				List<BpmHistoryEntity> oldh=historyQueryUtil.getEntitys(null, where, null, 1, 1);
				BpmHistoryEntity history1 =null;
				//d、设置项目待审批人信息
				String tsassignees="";
				boolean finder=false;
				if(oldh!=null && oldh.size()>0) {

					//3、第一个节点历史配置
					 history1 =oldh.get(0);
					 finder=true;
					//项目来源节点处理
					 if(fromTaskID.equals(history1.getfromtaskdefid())
							 || (history1.getfromtaskdefid()!=null && history1.getfromtaskdefid().contains(fromTaskID))) {
						 
					 }else {
						 if(history1.getfromtaskdefid()==null) {
								//a、设置项目来源信息
								history1.setfromtaskdefname(fromTaskName);
								history1.setfromtaskdefid(fromTaskID);
						 }else {
								//a、设置项目来源信息
								history1.setfromtaskdefname(history1.getfromtaskdefname()+","+fromTaskName);
								history1.setfromtaskdefid(history1.getfromtaskdefname()+","+fromTaskID);
						 }
					 }
					//用户处理
					 if(user.getUserId().equals(history1.getfromassigneesid())
							 || (history1.getfromassigneesid()!=null && history1.getfromassigneesid().contains(user.getUserId()))) {
						 
					 }else {
						 if(history1.getfromassigneesid()==null) {
								//a、设置项目来源信息
								history1.setfromassigneesid(user.getUserId());
								history1.setfromassigneesname(user.getUserName());
						 }else {
								//a、设置项目来源信息
								history1.setfromassigneesid(history1.getfromassigneesid()+","+user.getUserId());
								history1.setfromassigneesname(history1.getfromassigneesname()+","+user.getUserName());
						 }
					 }
					 //组织机构处理
					 if(user.getUserOrgCode().equals(history1.getfromorgid())
							 || (history1.getfromorgid()!=null && history1.getfromorgid().contains(user.getUserOrgCode()))) {
						 
					 }else {
						 if(history1.getfromorgid()==null) {
								//a、设置项目来源信息
								history1.setfromorgid(user.getUserOrgCode());
								history1.setfromorgname(user.getUserOrgName());
						 }else {
								//a、设置项目来源信息
								history1.setfromassigneesid(history1.getfromorgid()+","+user.getUserOrgCode());
								history1.setfromassigneesname(history1.getfromorgname()+","+user.getUserOrgName());
						 }
					 }
				}else {

					//3、第一个节点历史配置
					 history1 =historyEditUtl.CreateHistory(oInfo.getSexeid(), overWrokH.getactdefid(), user,itask, entity);
					//a、设置项目来源信息
					history1.setfromtaskdefname(fromTaskName);
					history1.setfromtaskdefid(fromTaskID);
					
					history1.setfromassigneesid(user.getUserId());
					history1.setfromassigneesname(user.getUserName());
					history1.setfromorgid(user.getUserOrgCode());
					history1.setfromorgname(user.getUserOrgName());
				}
				
				//b、设置项目历史状态信息
				if(index<1) {
					history1.sethistorystatus(historyStatus);
				}else {
					history1.sethistorystatus("1");
				}
				index++;
				
				//c、设置项目历史审批人问题
				String sassignees=","+user.getUserId()+","+user.getUserName();
				if(o_sassignees==null) {
					
				}else if(!o_sassignees.contains(sassignees)){
					sassignees=sassignees+","+o_sassignees;
				}else {
					sassignees=o_sassignees;
				}
				history1.setsassignees(sassignees);
				//d、设置项目待审批人信息
				//String tsassignees="";
				List<UserInfo> userlst=itask.getUser();
				for(UserInfo iuser:userlst) {
					if(iuser.getUserSelected() && !tsassignees.contains(tsassignees+","+iuser.getUserId()+",")) {
						tsassignees=tsassignees+","+iuser.getUserId()+","+iuser.getUserName()+",";
					}
				}
				
				history1.setToptassigneese(tsassignees);
				history1.setSread("0");
				
				//e、设置项目的下一个环节
				history1.setTasktype(workFlowDrive.getTaskStringType(oInfo.getbpmkey(),itask.getTaskdefinedid()));
				history1.setNexttask(this.nextTaskUtils.getNextTaskInfo(oInfo.getSexeid(), oInfo.getbpmkey(),itask.getTaskdefinedid(),entity).getNextTaskName());
				if(finder) {
					updatelst.add(history1);
				}else {
					if(bpmStatus!=null) {
						history1.setTaskstatus(bpmStatus);
					}
					addlst.add(history1);
				}
				
			}
		}
		String targerTaskid="";
		for(TaskInfo itask:oInfo.getNextTask()) {
			if(itask.isTaskSelect()) {
				targerTaskid=itask.getTaskdefinedid();
				break;
			}
		}
		this.workFlowDrive.JumpTask(oInfo.getSexeid(), targerTaskid);
		historyEditUtl.updateList(updatelst);
		historyEditUtl.addList(addlst);
	}
}
